package com.sharelords.spring.annotation;

import com.sharelords.biz.config.GeneralBizConfig;
import com.sharelords.biz.register.MemoryClassBeanRegister;
import com.sharelords.biz.util.InvokeUtil;
import com.sharelords.spring.config.ClassPathBizScanner;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 通用biz路径扫描及ioc注册器
 * @Author: 千古龙少
 * @Time: 2019/11/23 18:03
 */
public class BizScannerRegister implements ImportBeanDefinitionRegistrar {

    private static final String VALUE = "value";
    private static final String BASE_PACKAGES = "basePackages";
    private static final String DELETE_JAVA_FILE = "remainJavaSrcFile";
    private static final String SRC_FILE_PATH = "srcFilePath";

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AnnotationAttributes annotationAttrs = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(BizScan.class.getName()));

        // 扫描路径提取
        List<String> basePackages = new ArrayList<>();
        // value对应的路径
        String[] valuePackagesPath = annotationAttrs.getStringArray(VALUE);
        if (valuePackagesPath != null && valuePackagesPath.length > 0) {
            basePackages.addAll(Arrays.asList(valuePackagesPath));
        }
        // basePackages对应的路径
        String[] basePackagesPath = annotationAttrs.getStringArray(BASE_PACKAGES);
        if (basePackagesPath != null && basePackagesPath.length > 0) {
            basePackages.addAll(Arrays.asList(basePackagesPath));
        }
        if (basePackages.isEmpty()) {
            return;
        }

        // 加载配置参数
        GeneralBizConfig config = GeneralBizConfig.getInstance();
        config.basePackages = InvokeUtil.joinList2Str(basePackages);
        config.remainJavaSrcFile = annotationAttrs.getBoolean(DELETE_JAVA_FILE);
        config.srcFilePath = annotationAttrs.getString(SRC_FILE_PATH);

        // 开始扫描及动态生成class文件
        new ClassPathBizScanner(config).initMethod();

        // 向spring容器注册
        new MemoryClassBeanRegister(registry).regist();
    }
}
